package cz.muni.fi.pa165.rentalofconstructionmachinery.service.impl;

import cz.muni.fi.pa165.rentalofconstructionmachinery.dao.RevisionDAO;
import cz.muni.fi.pa165.rentalofconstructionmachinery.dto.MachineDTO;
import cz.muni.fi.pa165.rentalofconstructionmachinery.dto.RevisionDTO;
import cz.muni.fi.pa165.rentalofconstructionmachinery.dto.converters.MachineDTOConverter;
import cz.muni.fi.pa165.rentalofconstructionmachinery.dto.converters.RevisionDTOConverter;
import cz.muni.fi.pa165.rentalofconstructionmachinery.entity.Machine;
import cz.muni.fi.pa165.rentalofconstructionmachinery.entity.Revision;
import cz.muni.fi.pa165.rentalofconstructionmachinery.service.RevisionService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Adam Zmrzlý
 * @version Miura (20121101)
 */

@Service
public class RevisionServiceImpl implements RevisionService {

    @Autowired
    private RevisionDAO rDAO;

    @Override
    @Transactional
    public void create(RevisionDTO revision) {
        rDAO.createRevision(RevisionDTOConverter.dtoToEntity(revision));
    }

    @Override
    @Transactional
    public void delete(RevisionDTO revision) {
        rDAO.deleteRevision(RevisionDTOConverter.dtoToEntity(revision));
    }

    @Override
    @Transactional
    public void update(RevisionDTO revision) {
        rDAO.updateRevision(RevisionDTOConverter.dtoToEntity(revision));
    }

    @Override
    @Transactional(readOnly=true)
    public List<RevisionDTO> getAll() {
        List<Revision> revisions = rDAO.getAllRevisions();
        List<RevisionDTO> ret = new ArrayList<>();

        for(Revision r : revisions) {
            ret.add(RevisionDTOConverter.entityToDTO(r));
        }

        return ret;
    }

    @Override
    @Transactional(readOnly=true)
    public RevisionDTO getRevisionById(Long id) {
        Revision revision = rDAO.getRevisionById(id);

        return RevisionDTOConverter.entityToDTO(revision);
    }

    @Override
    @Transactional(readOnly=true)
    public RevisionDTO getLastRevisionOfMachine(MachineDTO machine) {
        Machine m = MachineDTOConverter.dtoToEntity(machine);
        Revision r = rDAO.getLastRevisionOfMachine(m);

        return RevisionDTOConverter.entityToDTO(r);
    }

    @Override
    @Transactional(readOnly=true)
    public List<RevisionDTO> getAllRevisionsOfMachine(MachineDTO machine) {
        Machine m = MachineDTOConverter.dtoToEntity(machine);
        List<Revision> revisions = rDAO.getAllRevisionsOfMachine(m);
        List<RevisionDTO> ret = new ArrayList<>();
        
        for(Revision r : revisions) {
            ret.add(RevisionDTOConverter.entityToDTO(r));
        }

        return ret;
    }
}
